package com.ftrend.printdemo.common;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.loopstack.gprint.utils.Command;
import com.loopstack.gprint.utils.EscCommand;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

public class PrintOrderUtils {
    //打印机宽度
    public static int PRINT_WIDTH = 80;
    //打印机点数
    public static int PRINT_POINT_UNIT = 8;
    //汉字宽度
    public static int PRINT_CHINESE_WIFTH = 24;
    //字符宽度
    public static int PRINT_CHAR_WIDTH = 12;


    static boolean isOnlyReturn = false;

    private static String unit="元";

    private static boolean isShow0 = true;
    private static boolean isShow1 = true;
    private static boolean isShow2 = true;
    private static boolean isShow3 = true;
    private static boolean isShow4 = true;
    private static boolean isShow5 = true;
    private static boolean isShow6 = true;


    static Handler handler=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0x00:
                    String tip=(String)msg.obj;
                    //showCustomToast(tip);
                    break;
                case 0x01:
                    int status=msg.arg1;
                    if (status==-1){//获取状态失败
                        //showCustomToast("打印机出错，请检查");
                    }else if (status==1){
                        //showCustomToast("状态走纸、打印");
                        return;
                    }else if (status==0){//状态正常
                        //Toast.makeText(mContext,"",Toast.LENGTH_SHORT).show();
                        return;
                    }else if (status==-2){//状态缺纸
                        //showCustomToast("请安装好打印纸");
                        return;
                    }else if (status==-3){//状态开盖
                        //showCustomToast("打印机开盖，请关闭");
                        return;
                    }else if (status==-4){
                        //showCustomToast("打印机过热，请稍后");
                        return;
                    }
                    break;
                case 0x02://关闭连接

                    break;
                case 0x03:

                    break;
            }
        }
    };

    /**
     * 发送充值票据
     */
    public static boolean sendReceiptWithResponse() throws UnsupportedEncodingException {

        if (PrinterBlue.isTicketConnect()) {
            try {
                Command command = PrinterBlue.getPortManager().getCommand();
                int status = PrinterBlue.getPrinterState(command,100);
                if (status != 0&&status!=1&&status!=-1) {//打印机处于不正常状态,则不发送打印任务
                    Message msg = new Message();
                    msg.what = 0x01;
                    msg.arg1 = status;
                    handler.sendMessage(msg);
                    return false;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if (PrinterTicketUsb.isTicketConnect()) {
            try {
                Command command = PrinterTicketUsb.getPortManager().getCommand();
                int status = PrinterTicketUsb.getPrinterState(command,100);
                if (status != 0&&status!=1&&status!=-1) {//打印机处于不正常状态,则不发送打印任务
                    Message msg = new Message();
                    msg.what = 0x01;
                    msg.arg1 = status;
                    handler.sendMessage(msg);
                    return false;
                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }

        String valueCopies = "0";
        String receiptPrintLayout = "0";
        String notice = "notice";
        String storeName = "";
        String wxQrCode = "";
        int productViewCostPrice = 0;



        EscCommand esc = new EscCommand();
        esc.addSetPrintingAreaWidth((short) PRINT_WIDTH);
        esc.addInitializePrinter();
        if (PRINT_WIDTH == 80) {
            PRINT_CHAR_WIDTH = 12;
        } else {
            PRINT_CHAR_WIDTH = 9;
        }
        byte tl = 1;
        esc.addPrintAndFeedLines((byte) 1);
        /* 设置打印居中 */
        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
        esc.addTurnEmphasizedModeOnOrOff(EscCommand.ENABLE.ON);
        /* 设置为倍高倍宽 */
        esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_2, EscCommand.HEIGHT_ZOOM.MUL_2);
        esc.addTurnDoubleStrikeOnOrOff(EscCommand.ENABLE.ON);
        // esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_1,EscCommand.HEIGHT_ZOOM.MUL_1);
        String name = "name";
        if (PRINT_WIDTH == 58) {
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
//            short width = (short) printTextFontA(storeName);
//            esc.addSetAbsolutePrintPosition(width);
            /* 打印文字 */

            esc.addText(name+"\n");
        } else {
            /* 设置打印

            居中 */
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            /* 打印文字 */
            esc.addText(name+"\n");
        }

        esc.addPrintAndLineFeed();
        /* 打印文字 */
        /* 取消倍高倍宽 */
        esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_1, EscCommand.HEIGHT_ZOOM.MUL_1);
        /* 设置打印左对齐 */
        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
        esc.addTurnEmphasizedModeOnOrOff(EscCommand.ENABLE.ON);


        String text =  "employeeName："+"employeeName";
        esc.addSetAbsolutePrintPosition(PRINT_WIDTH == 80 ? (short) printTextWidth(text) : (short) printTextWidth58(text));
        /* 打印文字 */
        esc.addText(text);
        esc.addPrintAndLineFeed();

        String saleDate = "makeTime";
        // esc.addSetAbsolutePrintPosition((short) printTextWidth("日期：" + saleDate));
        if (!TextUtils.isEmpty(saleDate)&& isShow0) {
            /* 打印文字 */
            esc.addText("saleDate：" + saleDate);
            esc.addPrintAndLineFeed();
        }

        String memberName = "memberName";
        if (!TextUtils.isEmpty(memberName) && isShow1) {
            /* 打印文字 */
            esc.addText( "memberName" + memberName);
            esc.addPrintAndLineFeed();
        }
        String mobile = "mobile";
        if (!TextUtils.isEmpty(mobile) && isShow2) {
            /* 打印文字 */
            esc.addText( "mobile：" + mobile);
            esc.addPrintAndLineFeed();
        }

        String balance = "balance";
        if (!TextUtils.isEmpty(memberName) && isShow3) {
            /* 打印文字 */
            esc.addText("balance：" + balance+unit);
            esc.addPrintAndLineFeed();
        }
        String point = "point";
        if (!TextUtils.isEmpty(memberName) && isShow4) {
            /* 打印文字 */
            esc.addText("point：" + point);
            esc.addPrintAndLineFeed();
        }

        String amount = "amount";
        if (!TextUtils.isEmpty(memberName)) {
            /* 打印文字 */
            esc.addText("amount"+ amount+unit);
            esc.addPrintAndLineFeed();
        }

        String present = "present";
        if (!TextUtils.isEmpty(memberName) && isShow5) {
            /* 打印文字 */
            esc.addText( "given_amount：" + present+unit);
            esc.addPrintAndLineFeed();
        }

        String payType ="payType"+"";
        if (!TextUtils.isEmpty(memberName) && isShow6) {
            switch (payType) {
                case "7":
                    payType ="扫码";
                    break;
                case "1":
                    payType ="现金";
                    break;
                case "2":
                    payType ="刷卡";
                    break;
                case "4":
                    payType ="微信" ;
                    break;
                case "5":
                    payType ="支付宝";
                    break;
            }
            esc.addText("payType："+ payType);
            esc.addPrintAndLineFeed();
        }

        esc.addPrintAndLineFeed();
        esc.addPrintAndLineFeed();
        esc.addPrintAndLineFeed();
        esc.addPrintAndLineFeed();
        esc.addCutAndFeedPaper((byte) 10);

        byte[] bytes = {29, 114, 1};
        esc.addUserCommand(bytes);
        Vector<Byte> datas = esc.getCommand();


        Vector<Byte> data = CloneUtils.clone(datas);
        if (PrinterTicketUsb.isTicketConnect()) {
            try {
                /* 发送数据 */
                boolean status = PrinterTicketUsb.getInstance().getPortManager().writeDataImmediately(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else  if (PrinterBlue.isTicketConnect()) {
            try {
                boolean status = PrinterBlue.getInstance().getPortManager().writeDataImmediately(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(PrinterEthernet.INSTANCE.isTicketConnect()){
            try {
                boolean status = PrinterEthernet.INSTANCE.getPortManager().writeDataImmediately(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    private static int printTextWidth(String text) {
        int chinestChar = getChineseLength(text);
        int notChinestChar = text.length() - chinestChar;
        return PRINT_WIDTH * PRINT_POINT_UNIT - PRINT_CHINESE_WIFTH * chinestChar - PRINT_CHAR_WIDTH * notChinestChar - PRINT_CHINESE_WIFTH * 3;
    }
    public static int getChineseLength(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 1;
            }
        }
        return valueLength;
    }

    private static int printTextWidth58(String text) {
        int chinestChar = getChineseLength(text);
        int notChinestChar = text.length() - chinestChar;
        return PRINT_WIDTH * PRINT_POINT_UNIT - 30 * chinestChar - PRINT_CHAR_WIDTH * notChinestChar - PRINT_CHINESE_WIFTH * 3;
    }
}
